package main

import (
	"fmt"
	"math/rand"
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func NewExporter(metricsPrefix string) *prometheus.Registry {
	gauge := prometheus.NewGauge(prometheus.GaugeOpts{
		Namespace: metricsPrefix,
		Name:      "gauge_metric",
		Help:      "This is a dummy gauge metric"})

	gaugeVec := *prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Namespace: metricsPrefix,
		Name:      "gauge_vec_metric",
		Help:      "This is a dummy gauga vece metric"},
		[]string{"myLabel"})

	r := prometheus.NewRegistry()
	r.MustRegister(gauge, gaugeVec)

	go func() {
		for {
			gauge.Set(float64(RandInt64(1, 100)))
			time.Sleep(2 * time.Second)
		}
	}()

	go func() {
		for {
			gaugeVec.WithLabelValues("jmz").Set(float64(RandInt64(1, 100)))
			gaugeVec.WithLabelValues("kkk").Set(float64(RandInt64(1, 100)))
			time.Sleep(1 * time.Second)
		}
	}()
	return r
}

func RandInt64(min, max int64) int64 {
	if min >= max || min == 0 || max == 0 {
		return max
	}
	rand.Seed(time.Now().UnixNano())
	return rand.Int63n(max-min) + min
}

func main() {
	fmt.Println(`
  This is a dummy example of prometheus exporter
  Access: http://127.0.0.1:8082
  `)

	// Define parameters
	metricsPath := "/metrics"
	listenAddress := ":8082"
	metricsPrefix := "dummy"

	// Launch http service
	http.Handle(metricsPath, promhttp.HandlerFor(NewExporter(metricsPrefix), promhttp.HandlerOpts{}))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
             <head><title>Dummy Exporter</title></head>
             <body>
             <h1>Dummy Exporter</h1>
             <p><a href='` + metricsPath + `'>Metrics</a></p>
             </body>
             </html>`))
	})
	fmt.Println(http.ListenAndServe(listenAddress, nil))
}
